package com.pass.util;

import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @ClassName FileUtil
 * @Description 文件操作工具类
 * @Author guchu
 * @Date 2021/1/3 18:24
 * @Version 1.0
 */
public class FileUtil {
    public static final String TAG = "FileUtil";
    private static OkHttpClient okHttpClient = new OkHttpClient();

    /**
     * 该函数，在rxjava2. 上传文件的时候，要使用到.
     *
     * @param file
     * @return
     */
    public static MultipartBody.Part getPart(File file) {
        String partName = "file";
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
        return MultipartBody.Part.createFormData(partName, file.getAbsolutePath(), requestFile);
    }

    /**
     * 下载文件工具类
     *
     * @param url           网络路径
     * @param localFilePath 下载到的本地路径（包括文件名）
     */
    public static boolean downloadFile(String url, String localFilePath) {
        Request request = new Request.Builder().url(url).build();
        Response response;
        InputStream inputStream = null;
        FileOutputStream fos = null;
        boolean downloadFlag = false;
        try {
            response = okHttpClient.newCall(request).execute();
            inputStream = response.body().byteStream();
            fos = new FileOutputStream(localFilePath);
            int len;
            byte[] buf = new byte[4096];
            while ((len = inputStream.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
            downloadFlag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (!downloadFlag) {
            File localFile = new File(localFilePath);
            if (localFile.exists()) {
                localFile.delete();
            }
        }
        return downloadFlag;
    }

    /**
     * 单层文件夹复制.
     */
    public static boolean copy1LayerFolder(File src1LayerFolder, File dst1LayerFolder) {
        if (Thread.currentThread().isInterrupted()) {
            return false;
        }
        if (!src1LayerFolder.exists()) {
            return false;
        }
        if (!dst1LayerFolder.exists()) {
            dst1LayerFolder.mkdirs();
        }
        File[] srcFiles = src1LayerFolder.listFiles();
        if (null == srcFiles || 0 == srcFiles.length) {
            return true;
        }

        for (int i = 0; i < srcFiles.length; i++) {
            File dstFile = new File(dst1LayerFolder, srcFiles[i].getName());
            boolean copyFlag = copyFile(srcFiles[i], dstFile);
            if (!copyFlag) {
                System.out.println(srcFiles[i].getAbsolutePath() + "复制失败,复制中断.");
                return false;
            }
        }
        return true;
    }


    /**
     * 文件复制，一个文件复制到另外一个文件中
     */
    public static boolean copyFile(File srcFile, File dstFile) {
        if (!srcFile.exists()) {
            return false;
        }
        File dstParentFile = dstFile.getParentFile();
        if (null == dstParentFile) {
            return false;
        }
        if (!dstParentFile.exists()) {
            dstParentFile.mkdirs();
        }

        if (dstFile.exists()) {
            dstFile.delete();
        }
        byte[] buffer = new byte[4096];
        InputStream is = null;
        OutputStream os = null;
        int length;
        try {
            is = new FileInputStream(srcFile);
            os = new FileOutputStream(dstFile);
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
                if (null != os) {
                    os.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 文件夹删除.
     * 写一个递归删除.
     */
    public static void deleteDir(File dstFile) {
        if (Thread.currentThread().isInterrupted()) {
            return;
        }
        if (!dstFile.exists()) {
            return;
        }
        File[] files = dstFile.listFiles();
        if (null == files || 0 == files.length) {
            return;
        }
        for (File file : files) {
            if (file.isFile()) {
                file.delete();
            }
            if (file.isDirectory()) {
                deleteDir(file);
            }
        }
        if (dstFile.isDirectory() && (null == dstFile.listFiles() || 0 == Objects.requireNonNull(dstFile.listFiles()).length)) {
            dstFile.delete();
        }
    }

    /**
     * 获取文件夹下所有文件的大小.
     *
     * @return
     */
    public static long getDirSize(File dirFile) {
        if (null == dirFile || !dirFile.exists()) {
            return 0L;
        }
        if (!dirFile.isDirectory()) {
            return dirFile.length();
        }
        return getDirSizeInner(dirFile);
    }

    private static long getDirSizeInner(File dirFile) {
        long sumSize = 0L;
        File[] files = dirFile.listFiles();
        if (null == files || 0 == files.length) {
            return 0L;
        }
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                sumSize += files[i].length();
            }
            if (files[i].isDirectory()) {
                sumSize += getDirSizeInner(files[i]);
            }
        }
        return sumSize;
    }


    public static long getAvailableRom() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSizeLong();
        long availableBlocks = stat.getAvailableBlocksLong();
//        Log.d(TAG, "blockSize : " + blockSize + ";   availableBlocks : " + availableBlocks + ";     " + "result : " + (blockSize * availableBlocks / 1000000) + ";");
//        Log.d(TAG, "result : " + (blockSize * availableBlocks / 1000000) + ";");
        return (int) (blockSize * availableBlocks >>> 30);//返回G
    }

}
